package com.zhiwang.planet.widget

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import androidx.annotation.StringRes
import androidx.appcompat.widget.AppCompatTextView
import androidx.appcompat.widget.Toolbar
import android.text.TextUtils
import android.util.AttributeSet
import android.view.Gravity

import com.zhiwang.planet.R

import android.view.ViewGroup.LayoutParams.WRAP_CONTENT

class CenterTitleToolBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.toolbarStyle) : Toolbar(context, attrs, defStyleAttr) {

    var myTitleTextView: AppCompatTextView? = null

    init {
        initialize(context, attrs, defStyleAttr)

    }

    @SuppressLint("PrivateResource")
    private fun initialize(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
        super.setTitle(null)
        val a = context.obtainStyledAttributes(attrs, R.styleable.Toolbar, defStyleAttr, 0)
        // same as ToolBar's default color
        val titleTextColor = a.getColor(R.styleable.Toolbar_titleTextColor, -0x1)
        //fetch the customized TextAppearance
        val appearance = a.getResourceId(R.styleable.Toolbar_titleTextAppearance, 0)
        val title = a.getString(R.styleable.Toolbar_title)
        a.recycle()
        myTitleTextView = AppCompatTextView(context)
        val layoutParams = Toolbar.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
        layoutParams.gravity = Gravity.CENTER
        myTitleTextView!!.layoutParams = layoutParams
        myTitleTextView!!.text = title
        myTitleTextView!!.setTextColor(titleTextColor)
        if (appearance != 0)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                myTitleTextView!!.setTextAppearance(appearance)
            } else {
                myTitleTextView!!.setTextAppearance(context, appearance)
            }
        else
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                myTitleTextView!!.setTextAppearance(R.style.TextAppearance_AppCompat_Title)
            } else {
                myTitleTextView!!.setTextAppearance(context, R.style.TextAppearance_AppCompat_Title)
            }
        addView(myTitleTextView)
    }


    //override  setting text to our own textview
    override fun setTitle(title: CharSequence) {
        if (TextUtils.equals(title, resources.getString(R.string.app_name)))
            return
        if (myTitleTextView != null) {
            myTitleTextView!!.text = title
        }
    }

    override fun setTitle(@StringRes resId: Int) {
        title = resources.getString(resId)
    }
}
